package cn.com.ytst.data.integration.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;


import com.google.common.collect.Maps;
import com.ytst.framework.common.StringTools;

import cn.com.ytst.data.integration.CommonKey;
import cn.com.ytst.data.integration.util.PageUtil;
import cn.com.ytst.data.integration.util.filter.FileFilter;
import cn.com.ytst.data.integration.vo.AjaxResult;
import cn.com.ytst.data.integration.vo.DataTable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName MQController
 * @Deacription mq组件
 * @Author Administrator
 * @Date 2020/6/20 0020 16:54
 * @Version 1.0
 **/
@Controller
@RequestMapping
@Slf4j
public class MQController {


	   @Value("${filepath}")
	   private String filepath;
	 
		private static final String LINE_TAG = File.separator;
		
		
		private static final String UTF_TAG = "utf-8";
		



	    @RequestMapping(value="/mq/grid",method= RequestMethod.POST)
	    @ResponseBody
	    public DataTable<JSONObject>  grid(HttpServletRequest request) throws IOException{
			String pageNumber = StringTools.isBlank(request.getParameter("pageNum"))?"1":request.getParameter("pageNum");
			String pageSize =  StringTools.isBlank(request.getParameter("pageSize")) ? "10":request.getParameter("pageSize");
	    	List<File> list = FileFilter.fiterFile(filepath+LINE_TAG+"mq", "mq");
	    	List<JSONObject> list_json = Lists.newArrayList(); 
	    	if(!list.isEmpty()) {
	    		for(File f : list) {
	    		JSONObject jsonObject = new JSONObject();
 			    Configuration configuration = Configuration.from(FileUtils.readFileToString(f, UTF_TAG));
 			    String host = configuration.getString(CommonKey.MQ_HOST_TAG);
 			    String port = configuration.getString(CommonKey.MQ_PORT_TAG);
 		        String queue = configuration.getString(CommonKey.MQ_QUEUE_TAG);
 		        String type = configuration.getString(CommonKey.MQ_TYPE_TAG);//消息中间件类型
 		        String datatype = configuration.getString(CommonKey.MQ_DATA_TRANS_TAG);//消息中间件类型
 		        //boolean stateflage = AbstractCamelContainer.getCamelMap().containsKey(f.getName());
 			    jsonObject.put("state", false?"正在消费":"停止消费");//当前是否开启和停止状态
 			    jsonObject.put("mqtype", type);
 			    jsonObject.put("datatype", datatype);
 			    jsonObject.put("host", host);
 			    jsonObject.put("port", port);
 			    jsonObject.put("queue", queue);
 			    jsonObject.put("id",f.getName());
 			    list_json.add(jsonObject);
	    		}
	    	}
	    	DataTable<JSONObject> dataTable = new DataTable<>();
	    	dataTable.setRows(PageUtil.startPage(list_json,Integer.parseInt(pageNumber),Integer.parseInt(pageSize)));
	    	dataTable.setTotal(list_json.size());
	    	dataTable.setCode(0);
	    	dataTable.setMsg("");
	    	return dataTable;
	    	
	    }
	    
	    
	    @RequestMapping(value="/mq/edit/{id}",method= RequestMethod.GET)
	    public ModelAndView edit(@PathVariable(value = "id") String id) {
	    	Configuration configuration = Configuration.from(new File(filepath+File.separator+"mq"+File.separator+id));
	    	Set<String> set = configuration.getKeys();
	    	Map<String,Object> map = Maps.newHashMap();
	    	for(String key : set) {
	    		int last_index = key.lastIndexOf(".");
	    		String end_key = key.substring(last_index+1);
	    		if("is_batch".equals(end_key)) {
	    			map.put(end_key, (boolean)configuration.get(key) ?"2":"1");
	    		}else if("encrypt".equals(end_key)) {
	    			map.put(end_key, (boolean)configuration.get(key) ?"1":"2");
	    		}
	    		else {
	    			map.put(end_key, Objects.toString(configuration.get(key),""));
	    		}
	    	}
	    	if(!map.containsKey("datatype")) {
	    		map.put("datatype", "");
	    	}
	    	map.put("id", id);

	    	return  new ModelAndView("/page/component/mq/mq-edit",map);
	    }
	    @RequestMapping(value="/mq/add",method= RequestMethod.GET)
	    public String add() {
	    	return "/page/component/mq/mq-add";
	    }

	    /**
	    * @Title: save
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param  《HOST名称》 支持集群方式配置：配置方法样例  10.10.3.166:9876;10.10.3.167;
	    *        最后一个集群机器不配置端口号   最后一台机器端口号在  页面《端口号》  配置  样例 9876
	    * @return AjaxResult    返回类型
	    * @throws
	    */
	    @RequestMapping(value="/mq/save",method= RequestMethod.POST)
	    @ResponseBody
	    public AjaxResult save(HttpServletRequest request) {
	    	String encrypt = request.getParameter("encrypt");
	    	String mqtype = request.getParameter("mqtype");
	    	String is_batch = request.getParameter("is_batch");
            String filename = request.getParameter("filename");
	    	String host = request.getParameter("host");
            String pluginname = request.getParameter("pluginname");
	    	String port = request.getParameter("port");
	    	String tags = StringTools.mkString(request.getParameter("tags"));//这个只针对rocketmq的，其它的没有改属性  子主题
	    	String username = request.getParameter("username");
	    	String password = request.getParameter("password");
	    	String queue = request.getParameter("queue");
	    	String table_name = request.getParameter("table_name");
	    	String datatype = request.getParameter("datatype");
	    	String filetag = StringTools.isBlank(tags) ? "":"_"+StringTools.isBlank(tags);
			File file = new File(filepath+File.separator+"mq"+File.separator+(filename.startsWith("mq")? StringTools.mkString(filename+tags).toLowerCase():StringTools.mkString("mq_"+filename+filetag).toLowerCase())+".json");

	    	try {
	    		 String str = FileUtils.readFileToString(new File(filepath+"/temp/mq_temp.json"),UTF_TAG);
				 FileUtils.write(file, str, UTF_TAG);//先预先创建一个文件
				 Configuration configuration = Configuration.from(file);
				 configuration.set(CommonKey.MQ_QUEUE_TAG, queue);
				 configuration.set(CommonKey.MQ_PLUGINNAME_TAG,pluginname);
				 configuration.set(CommonKey.MQ_TAGS_TAG, tags);
				 configuration.set(CommonKey.MQ_USERNAME_TAG, username);
				 configuration.set(CommonKey.MQ_IS_BATCH, Integer.parseInt(is_batch) == 2 ?true:false);
				 configuration.set(CommonKey.MQ_PWD_TAG, password);
				 configuration.set(CommonKey.MQ_PORT_TAG,port);
				 configuration.set(CommonKey.MQ_DATA_TRANS_TAG, datatype);
				 configuration.set(CommonKey.MQ_ENCRYPT_TAG, Integer.parseInt(encrypt) ==1 ?true:false);
				 configuration.set(CommonKey.MQ_HOST_TAG,host);
				 configuration.set(CommonKey.MQ_TABLE_NAME,table_name);
				 configuration.set(CommonKey.MQ_TYPE_TAG, StringTools.mkString(mqtype));
				 String json = configuration.beautify();
				 FileUtils.write(file, json, UTF_TAG);//先预先创建一个文件
				 return AjaxResult.success(filename+"添加成功!");
			} catch (IOException e) {
				e.printStackTrace();
			}
	    	 return AjaxResult.error(filename+"添加失败!");

	    }


	    @RequestMapping(value="/mq/update",method= RequestMethod.POST)
	    @ResponseBody
	    public AjaxResult update(HttpServletRequest request) {
	    	String name = request.getParameter("plguinname");
	    	String encrypt = request.getParameter("encrypt");
	    	String mqtype = request.getParameter("mqtype");
	    	String is_batch = request.getParameter("is_batch");
	    	String host = request.getParameter("host");
	    	String port = request.getParameter("port");
	    	String username = request.getParameter("username");
	    	String password = request.getParameter("password");
	    	String queue = request.getParameter("queue");
	    	String datatype = request.getParameter("datatype");
	    	String topic = request.getParameter("topic");
	    	String key = request.getParameter("key");
	    	String table_name = request.getParameter("table_name");
	    	String tags = StringTools.mkString(request.getParameter("tags"));//这个只针对rocketmq的，其它的没有改属性
	    	String id = request.getParameter("id");
	    	File file = new File(filepath+LINE_TAG+"mq"+LINE_TAG+id);

	    	try {
	    		 String str = FileUtils.readFileToString(file,UTF_TAG);
				 Configuration configuration = Configuration.from(str);
				 configuration.set(CommonKey.MQ_QUEUE_TAG, queue);
				 configuration.set(CommonKey.MQ_TAGS_TAG, tags);
				 configuration.set(CommonKey.MQ_USERNAME_TAG, username);
				 configuration.set(CommonKey.MQ_IS_BATCH, Integer.parseInt(is_batch) == 2 ?true:false);
				 configuration.set(CommonKey.MQ_PWD_TAG, password);
				 configuration.set(CommonKey.KAFKA_TOPIC_TAG, topic);
				 configuration.set(CommonKey.KEY_TAG, key);
				 configuration.set(CommonKey.MQ_DATA_TRANS_TAG, datatype);
				 configuration.set(CommonKey.MQ_PLUGINNAME_TAG, name);
				 configuration.set(CommonKey.MQ_PORT_TAG,port);
				 configuration.set(CommonKey.MQ_ENCRYPT_TAG, Integer.parseInt(encrypt) ==1 ?true:false);
				 configuration.set(CommonKey.MQ_HOST_TAG,host);
				 configuration.set(CommonKey.MQ_TABLE_NAME,table_name);
				 configuration.set(CommonKey.MQ_TYPE_TAG,StringTools.mkString(mqtype));
				 String json = configuration.beautify();
				 FileUtils.write(file, json, UTF_TAG);//先预先创建一个文件
				 return AjaxResult.success(id.substring(0,id.lastIndexOf("."))+"编辑成功!");
			} catch (IOException e) {
				e.printStackTrace();
			}
	    	 return AjaxResult.error(id.substring(0,id.lastIndexOf("."))+"编辑失败!");

	    }
//
//	    
//	    @RequestMapping(value="/mq/start",method= RequestMethod.POST)
//	    @ResponseBody
//	    public AjaxResult start(String id) {
//	    	String path = this.filepath+LINE_TAG+"mq"+LINE_TAG+id;
//	    	File f = new File(path);
//	    	 boolean stateflage = CamelContainer.getCamelMap().containsKey(f.getName());
//	         if(stateflage) {
//	           return AjaxResult.error(id+"作业已经消费中!");
//	         }
//	         String result = mqEngine.engin(path);
//	         if(StringTools.isEquals(result, DictionaryEnu.SUCCESS.name())) {
//	        	 return AjaxResult.success(id+"作业开始消费!");
//	         }else {
//	        	 return AjaxResult.error(id+"作业开始消费失败!");
//	         }
//	    }
//	    
//	    @RequestMapping(value="/mq/stop",method= RequestMethod.POST)
//	    @ResponseBody
//	    public AjaxResult stop(String id) {
//	    	try {
//	    		File f = new File(this.filepath+LINE_TAG+"mq"+LINE_TAG+id);
//	    		new ActiveMqCamelContainer(f).doStop();
//				 return AjaxResult.success(id+"作业开始消费停止消费!");
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//	    	 return AjaxResult.error(id+"作业开始消费停止消费失败!");
//
//	    }

	@RequestMapping(value="/mq/remove",method= RequestMethod.POST)
	@ResponseBody
	public AjaxResult delete(String ids){
		try {
	    		 File f = new File(this.filepath+LINE_TAG+"mq"+LINE_TAG+ids);
	    		 FileUtils.forceDelete(f);
				 return AjaxResult.success(ids+"删除成功!");
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	 return AjaxResult.error(ids+"删除失败!");
	}
	    
}
